//
//  KABTicketDetailVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/2/16.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABTicketDetailVC.h"
#import "KABTicketDetailTCell.h"
#import "KABModel.h"
#import "NSString+XDNSDate.h"
#import "NSDate+XDTimerFormatter.h"
#import "MBProgressHUD+XDPrompt.h"
#import "GlobalHeader.h"
#import "XDAFNetworking.h"
#import "ApiManager.h"

@interface KABTicketDetailVC ()<UITableViewDelegate, UITableViewDataSource>
@property (strong, nonatomic) IBOutlet UIView *headerBgView;
@property (strong, nonatomic) IBOutlet UIView *footerBgView;
@property (weak, nonatomic) IBOutlet UILabel *headerTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *headerTicketLabel;
@property (weak, nonatomic) IBOutlet UILabel *headerPriceLabel;
@property (weak, nonatomic) IBOutlet UILabel *headerTimeLabel;
@property (weak, nonatomic) IBOutlet UIImageView *headerEndImgView;


@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

static NSString *const kReuseCellId = @"KABTicketDetailTCell";

@implementation KABTicketDetailVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initNavigationBar {
    self.navigationItem.title = @"门票二维码";
    
    if (self.presentingViewController) {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(closeBarBtnTapped:)];
    }
}

- (void)initSubViews {
    UINib *nib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 45.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.tableView.tableHeaderView = self.headerBgView;
    self.tableView.tableFooterView = self.footerBgView;
//    self.tableView.sectionHeaderHeight = UITableViewAutomaticDimension;
//    self.tableView.estimatedSectionHeaderHeight = 6;
//    self.tableView.sectionFooterHeight = UITableViewAutomaticDimension;
//    self.tableView.estimatedSectionFooterHeight = 6;
    
    [self refreshWholeView];
    if (!self.ticketDetail) {
        [self requestTicketDetail];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KABTicketDetailTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
    [cell configViewWithExhOrderDetail:self.ticketDetail];
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 6;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 6;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ;
}

#pragma mark - event response
- (void)closeBarBtnTapped:(UIBarButtonItem *)item {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - private methods
- (void)refreshWholeView {
    // 尾部加载更多的显示
    //    if (self.model.taskList.count >= self.model.totalCount) {
    //        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    //    } else {
    //        [self.tableView.mj_footer resetNoMoreData];
    //    }
    
    self.headerTitleLabel.text = self.ticketDetail.exhibition_name;
    self.headerTicketLabel.text = [NSString stringWithFormat:@"电子票x%zd", self.ticketDetail.number];
    self.headerPriceLabel.text = [NSString stringWithFormat:@"总价：￥%.2f", self.ticketDetail.total_price / 100.0];
    NSString *startTime = [[self.ticketDetail.exhibition_starttime xd_yyyyMMddHHmmssStrToDate] xd_yyyyMMddHHmm];
    NSString *endTime = [[self.ticketDetail.exhibition_endtime xd_yyyyMMddHHmmssStrToDate] xd_MMddHHmm];
    self.headerTimeLabel.text = [NSString stringWithFormat:@"时间：%@ - %@", startTime, endTime];
    self.headerEndImgView.hidden = !self.ticketDetail.is_expired;
    
    [self.tableView reloadData];
}
#pragma mark - network request
- (void)requestTicketDetail {
    // 请求购物车必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    NSMutableDictionary *pars = [NSMutableDictionary dictionary];
    [pars setObject:self.order_id forKey:@"order_id"];
    if ([KABModel sharedInstance].isLogin) {
        [pars setObject:@([KABModel sharedInstance].userInfo.uid) forKey:@"user_id"];
        [pars setObject:[KABModel sharedInstance].userInfo.access_token forKey:@"access_token"];
    }
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiExhibitionOrder] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求展会详情返回：%@", responseObject);
        [hud hideAnimated:YES];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            self.ticketDetail = [KABExhOrderDetail yy_modelWithDictionary:responseObject[KABGlobalJsonKeyResult]];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求展会详情失败：%@", error);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

#pragma mark - getters and setters

@end
